package com.mgq.juc.philosopher;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author MaGuangQi
 * 哲学家就餐问题 (会产生死锁问题)
 * 解决办法是 使用 ReentrantLock
 * @date 2021-12-16 16:20
 **/
public class TestPhilosopher {
    public static void main(String[] args) {
        Chopstick c1 = new Chopstick("1");
        Chopstick c2 = new Chopstick("2");
        Chopstick c3 = new Chopstick("3");
        Chopstick c4 = new Chopstick("4");
        Chopstick c5 = new Chopstick("5");
        new Philosopher("姚二", c1, c2).start();
        new Philosopher("张三", c2, c3).start();
        new Philosopher("李四", c3, c4).start();
        new Philosopher("王五", c4, c5).start();
        new Philosopher("赵六", c5, c1).start();
    }

}

/**
 * 哲学家类
 */
@Slf4j
class Philosopher extends Thread{
    private String name;

    private Chopstick left;
    private Chopstick right;

    public Philosopher(String name, Chopstick left, Chopstick right) {
        super(name);
        this.name = name;
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            //synchronized会产生死锁
           /* synchronized (left) {
                synchronized (right) {
                    eat();
                }
            }*/
            //使用reentrantLock来解决
            if (left.tryLock()) {
                try {
                    if (right.tryLock()) {
                        try {
                            eat();
                        }finally {
                            right.unlock();
                        }
                    }
                }finally {
                    left.unlock();
                }
            }
        }
    }

    private void eat() {
        try {
            sleep(1000);
            log.debug("{},吃饭了",name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

/**
 * 筷子
 */
class Chopstick extends ReentrantLock {
    private String name;

    public Chopstick(String name) {
        this.name = name;
    }
}
